package com.tccmeta.servlce;

import com.tccmeta.constants.MetaConstants;
import com.tccmeta.po.Meta;
import org.springframework.stereotype.Service;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.List;

/**
 * @author pan
 * 执行GROOVY脚本
 */
@Service
public class GroovyService {
    public void beforeSave(List<Meta> scripts, Meta data) throws ScriptException {
        if (scripts != null) {
            for (Meta item : scripts) {
                for ( Meta child : item.getRelations()) {
                    if (!MetaConstants.BACK_SCRIPTS.equals(child.getOneDimensional())) {
                        continue;
                    }
                    String script = (String) child.getData();
                    ScriptEngineManager factory = new ScriptEngineManager();
                    ScriptEngine engine = factory.getEngineByName("groovy");
                    Bindings bindings = engine.createBindings();
                    bindings.put("REQUEST", data);
                    engine.eval(script, bindings);
                }
            }
        }

    }
}
